package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.xml.ws.runtime.dev.Session;

import service.PositionCommentService;
import service.PositionService;
import service.UserService;
import entityJDBC.PositionDescription;
import entityJPA.Position;
import entityJPA.Positioncomment;
import entityJPA.Positiondescription;
import entityJPA.User;

/**
 * Servlet implementation class PositionCommentServiceServlet
 */
@WebServlet("/PositionCommentServiceServlet")
public class PositionCommentServiceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int idPosition;
	private boolean ok = false;
	@EJB
	PositionCommentService positionCommentService;
	@EJB
	PositionService positionService;
	@EJB
	UserService userService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PositionCommentServiceServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession h = request.getSession();
		boolean sem=false;
		try{
			idPosition = Integer.parseInt(request.getParameter("positionId"));
			request.getSession().setAttribute("idPos", idPosition);
			sem=true;
		}
		catch(Exception e) {
			try{
				idPosition = Integer.parseInt(request.getParameter("idPosition"));
				request.getSession().setAttribute("idPos", idPosition);
				sem=true;
			}catch(Exception ex) {
				sem=false;
			}
		}
		if (sem){
		if (request.getSession().getAttribute("idPos")!=null)
			doPost(request, response);
		} else {
			// code for the error idPosition and idPositionDescription
			// inexistent
			h.setAttribute("exceptionMessage",
					"This position does not exist in the database.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
		
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession h = request.getSession();
		h.setAttribute("operationIsSuccesful", "");
		try {
			try {
				idPosition = (int)request.getSession().getAttribute("idPos");
			} catch (Exception e) {
				idPosition = (int)request.getSession().getAttribute("idPos");

			}
			List<Positioncomment> pc = positionCommentService
					.findAllCommentsByPosition(idPosition);
			if (pc.size() == 0 || pc.equals(null))
				request.setAttribute("message",
						"There are no comments for this position");
			else
				request.setAttribute("message", "");

			request.setAttribute("allPositionComments", positionCommentService
					.findAllCommentsByPosition(idPosition));
			Positiondescription positionDescription = positionService
					.getPositionById(idPosition).getPositiondescription();
			request.setAttribute("positionRequirements",
					positionDescription.getRequirements());
			request.setAttribute("positionResponsabilities",
					positionDescription.getResponsabilities());
			request.setAttribute("positionProject",
					positionDescription.getProject());
			request.setAttribute("positionName", positionService
					.getPositionById(idPosition).getName());
			request.setAttribute("index", 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (request.getParameter("insert") != null) {
			request.setAttribute("messageUser", "");
			add(request, response);
		} else if (request.getParameter("update") != null) {
			edit(request, response);
		} else if (request.getParameter("remove") != null) {
			delete(request, response);

		}
		Positiondescription positionDescription = positionService
				.getPositionById(idPosition).getPositiondescription();
		request.setAttribute("positionRequirements",
				positionDescription.getRequirements());
		request.setAttribute("positionResponsabilities",
				positionDescription.getResponsabilities());
		request.setAttribute("positionProject",
				positionDescription.getProject());
		request.setAttribute("positionName",
				positionService.getPositionById(idPosition).getName());
		request.setAttribute("idPosition", idPosition);
		request.setAttribute("allPositionComments",
				positionCommentService.findAllCommentsByPosition(idPosition));
		if (positionCommentService.findAllCommentsByPosition(idPosition).size() == 0)
			request.setAttribute("message",
					"There are no comments for this position");
		else
			request.setAttribute("message", "");
		if (ok == true) {
			h.setAttribute("operationIsSuccesful", "yes");
		} else {
			h.setAttribute("operationIsSuccesful", "no");
		}
		request.getRequestDispatcher("./positionComment.jsp").forward(request,
				response);

	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		String comment = request.getParameter("comment");
		String userName = (String) request.getSession().getAttribute(
				"savedUserName");
		User u = userService.getUserByUserName(userName);
		Positioncomment positionComment = new Positioncomment();
		positionComment.setComment(comment);
		positionComment.setUser(u);
		Position p = new Position();
		p.setIdPosition((int)request.getSession().getAttribute("idPos"));
		positionComment.setPosition(p);
		try {
			positionCommentService.insert(positionComment);
			ok = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void delete(HttpServletRequest request, HttpServletResponse response) {
		String userName = (String) request.getSession().getAttribute(
				"savedUserName");
		Positioncomment positionComment = positionCommentService
				.findPositionCommentById(Integer.parseInt(request
						.getParameter("idPositionComment")));
		if (positionComment.getUser().getUsername().equalsIgnoreCase(userName)) {
			try {
				positionCommentService.delete(positionComment);
				ok = true;
			} catch (Exception e) {

				e.printStackTrace();
			}

			request.setAttribute("messageUser", "");
		} else {
			ok = false;
			request.setAttribute("messageUser",
					"Comentariul nu apartine userului curent");
		}
	}

	private void edit(HttpServletRequest request, HttpServletResponse response) {
		Positioncomment positioncomment = new Positioncomment();
		int idPositionComment = Integer.parseInt(request
				.getParameter("idPositionComment"));
		String userName = (String) request.getSession().getAttribute(
				"savedUserName");
		positioncomment = positionCommentService
				.findPositionCommentById(idPositionComment);
		if (positioncomment.getUser().getUsername().equalsIgnoreCase(userName)) {
			try {
				positioncomment.setComment(request.getParameter("comment"));
				positionCommentService.update(positioncomment);
				ok = true;
				request.setAttribute("messageUser", "");
			} catch (Exception e) {

				e.printStackTrace();
			}
		} else {
			ok = false;
			request.setAttribute("messageUser",
					"Comentariul nu apartine userului curent");
		}

	}

	
}
